import fs from 'fs'
import path from 'path'
import json from '@rollup/plugin-json'
import vue from 'rollup-plugin-vue'
import postcss from 'rollup-plugin-postcss'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import { nodeResolve } from '@rollup/plugin-node-resolve'

export default {
  input: './src/index.js',
  output: [
    {
      format: 'cjs',
      file: './dist/azUI.cjs.min.js',
      sourcemap: true,
    },
    {
      format: 'es',
      file: './dist/azUI.es.min.js',
      sourcemap: true,
    },
  ],
}

// 公共插件配置
const plugins = [
  vue({
    css: true,
    compileTemplate: true,
  }),
  json(),
  nodeResolve(),
  postcss({
    // inject: true, // 把 css 插入到 style 中
    extract: true, // 把 css 放到和js同一目录
  }),
  babel({
    exclude: '**/node_modules/**',
  }),
  terser(),
]

const root = path.resolve(__dirname, 'packages')

module.exports = fs
  .readdirSync(root)
  // 过滤，只保留文件夹
  .filter((item) => fs.statSync(path.resolve(root, item)).isDirectory())
  .map((item) => {
    // @rollup/plugin-json 使 rollup 可以使用 require 的方式将 json 文件作为模块加载，并返回json对象
    const pkg = require(path.resolve(root, item, 'package.json'))
    return {
      input: path.resolve(root, item, 'index.js'),
      output: [
        {
          exports: 'auto',
          file: path.resolve(root, item, pkg.main),
          format: 'cjs',
        },
        {
          exports: 'auto',
          file: path.join(root, item, pkg.module),
          format: 'es',
        },
      ],
      plugins: plugins,
    }
  })
